package com.ftw.commons.widgets.refresh

import android.annotation.SuppressLint
import android.content.Context
import android.text.TextUtils
import android.util.AttributeSet
import android.util.SparseArray
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.jakewharton.rxbinding3.view.clicks
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.SimpleMultiPurposeListener
import com.ftw.commons.R
import kotlinx.android.synthetic.main.view_pull_and_refresh.view.*

/**
 * 描    述：分页加载专用View
 * 作    者：fantianwen
 * 时    间：2019/3/19  7:05 PM
 */
class PagingLoadRefreshLayout(val mContext: Context, attr: AttributeSet) :
    LinearLayout(mContext, attr) {

    private var mAdapter: BaseRecyclerViewAdapter<*>? = null
    private var mCallBack: CallBack? = null
    private var isRefresh: Boolean = false

    companion object {
        const val pageSize = 10
    }

    init {
        View.inflate(context, R.layout.view_pull_and_refresh, this)
    }

    /**
     * 设置列表后的注脚
     */
    fun setFootContent(content: String): PagingLoadRefreshLayout {
        tv_footer.visibility = View.VISIBLE
        tv_footer.text = content
        return this
    }

    fun setFootContentShow(isShow: Boolean, footText: String) {
        tv_footer.text = footText
        tv_footer.visibility = if (isShow) View.VISIBLE else View.GONE
    }

    //设置无数据状态下的View
    @SuppressLint("CheckResult")
    fun setEmptyView(content: Int, drawable: Int) {
        empty_view.setContent(resources.getString(content))
        empty_view.setImg(drawable)
        empty_view
            .clicks()
            .subscribe {
                mCallBack?.refresh(1)
            }

    }

    @SuppressLint("CheckResult")
    fun create(
        adapter: BaseRecyclerViewAdapter<*>,
        callBack: CallBack,
        isIncremental: Boolean = false
    ): PagingLoadRefreshLayout {
        mCallBack = callBack
        mAdapter = adapter
        recycler_view.setHasFixedSize(true)
        val layoutManager = WrapContentLinearLayoutManager(
            mContext,
            LinearLayoutManager.VERTICAL,
            false
        )
        recycler_view.layoutManager = layoutManager
        recycler_view.setHasFixedSize(false)
        recycler_view.isNestedScrollingEnabled = false
        recycler_view.adapter = mAdapter
        swipe_refresh_layout.setOnMultiPurposeListener(object : SimpleMultiPurposeListener() {
            override fun onRefresh(refreshLayout: RefreshLayout?) {
                //是不是增量列表，增量列表，不需要清除原来列表的数据
                if (!isIncremental) {
                    val size = mAdapter!!.getData().size
                    mAdapter!!.getData().clear()
                    mAdapter!!.notifyItemRangeRemoved(0, size)
                }
                mCallBack!!.refresh(1)
                isRefresh = true
            }

            override fun onLoadMore(refreshLayout: RefreshLayout?) {
                mCallBack!!.loadMore(getPage() + 1)
                isRefresh = false
            }

        })

        return this
    }


    /**
     * 获取当前分页Page
     */
    fun getPage(): Int {
        return mAdapter!!.itemCount / pageSize
    }

    /**
     * 是否还有下一页
     * isHasNextPage: true还有下一页，false没有下一页了,
     * footText:String 底部文字
     */
    @SuppressLint("CheckResult")
    fun loadComplete(isHasNextPage: Boolean, footText: String) {

        when (isRefresh) {
            true -> {
                swipe_refresh_layout.finishRefresh()
            }
            else -> {
                swipe_refresh_layout.finishLoadMore()
            }
        }



        mAdapter?.let {
            when (it.getData().size == 0) {
                true -> {
                    empty_view.visibility = View.VISIBLE
                    recycler_view.visibility = View.GONE
                    tv_footer.visibility = View.GONE
                }
                else -> {
                    empty_view.visibility = View.GONE
                    recycler_view.visibility = View.VISIBLE
                    it.notifyDataSetChanged()
                }
            }
        }

        //加载跟多
        when (!isRefresh) {

            true -> {
                //没有下一页了
                when (!isHasNextPage && mAdapter!!.getData().size > 0) {
                    true -> {
                        swipe_refresh_layout.finishLoadMoreWithNoMoreData()
                        if (!TextUtils.isEmpty(footText)) {
                            tv_footer.visibility = View.VISIBLE
                            tv_footer.text = footText
                        } else {
                            tv_footer.visibility = View.GONE
                        }

                    }
                    else -> {
                        swipe_refresh_layout.setNoMoreData(false)
                        tv_footer.visibility = View.GONE
                    }

                }

            }
        }

    }


    fun refreshData() {
        swipe_refresh_layout.autoRefresh()
    }

    fun disableRefresh() {
        swipe_refresh_layout.isEnableRefresh = false
    }

    fun disableLoadMore() {
        swipe_refresh_layout.isEnableLoadMore = false
    }

    fun restoreLoadMore() {
        swipe_refresh_layout.setNoMoreData(false)
    }

    /**
     * 监听回调
     */
    interface CallBack {
        /**
         * 刷新
         */
        fun refresh(page: Int)

        /**
         * 加载更多
         */
        fun loadMore(page: Int)
    }

}


@Suppress("UNCHECKED_CAST")
abstract class BaseRecyclerViewAdapter<T>(
    var mContext: Context,
    var mData: ArrayList<T>,
    private var mLayout: PagingLoadRefreshLayout
) :
    RecyclerView.Adapter<BaseRecyclerViewAdapter.ViewHolder>() {
    var mItemOnClick: ItemClick<T>? = null
    override fun getItemCount(): Int {
        return mData.size
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {

        val view = LayoutInflater.from(mContext).inflate(getViewId(), parent, false)
        val viewHolder = ViewHolder(view)
        val itemView = viewHolder.itemView

        itemView
            .setOnClickListener {
                val adapterPosition = viewHolder.adapterPosition
                if (adapterPosition != RecyclerView.NO_POSITION) {
                    onItemClick(itemView, adapterPosition)
                }
            }

        itemView.setOnLongClickListener {
            onItemLongClick(itemView, position = viewHolder.adapterPosition)
            true
        }
        return viewHolder
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        bindHolder(holder, mData[position])
    }

    open class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        private val views = SparseArray<View>()
        fun <T : View> getView(viewId: Int): T {
            var view = views[viewId]
            if (view == null) {
                view = itemView.findViewById(viewId)
                views.put(viewId, view)
            }
            return view as T
        }

    }

    /**
     * 添加数据
     */
    fun loadComplete(data: ArrayList<T>, isHasNextPage: Boolean, footText: String) {
        mData.addAll(data)
        mLayout.loadComplete(isHasNextPage, footText)
    }

    /**
     * 修改数据 0 是最开始添加数据，  1 后来数据刷新
     */
    abstract fun updateData(operating: Int, data: T)

    abstract fun bindHolder(holder: ViewHolder?, t: T)

    /**
     * 获取数组
     */
    fun getData(): ArrayList<T> {
        return mData
    }

    /**
     * 创建ViewHolder
     */
    abstract fun getViewId(): Int


    open fun onItemClick(itemView: View, position: Int) {
        mItemOnClick?.onItemOnClick(itemView, mData[position])
    }

    open fun onItemLongClick(itemView: View, position: Int) {
        mItemOnClick?.onItemLongClick(itemView, mData[position])
    }

    /**
     * 设置Item点击事件
     */
    fun setItemClick(itemClick: ItemClick<T>) {
        mItemOnClick = itemClick
    }


    interface ItemClick<T> {
        /**
         * item点击事件
         */
        fun onItemOnClick(itemView: View, t: T)

        /**
         * 长按事件
         */
        fun onItemLongClick(itemView: View, t: T)
    }


}




